package com.btr.ivle;

import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.btr.ivle.R;
import com.btr.ivle.backgroud.AsyncTaskCompleteListener;
import com.btr.ivle.backgroud.GetForumTask;
import com.btr.ivle.data.ForumData;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.ForumSeparatedListAdapter;
import com.btr.ivle.helper.IsNetworkAvailable;

public class ListForumPostActivity extends SherlockListActivity implements 
	AsyncTaskCompleteListener<String> {
	
	private Context context = this;
	private GetForumTask getForumPostTask;
	private List<Map<String, String>> list;
	private String ForumID, CourseCode;
	private MenuItem item;
	private boolean isRefresh = false;
	private boolean isEmpty = true;
	public static String MSG_PostID = "ListForumPostActivity.PostID";
	public static String MSG_ForumID = "ListForumPostActivity.ForumID";
	public static String MSG_HeadingID = "ListForumPostActivity.HeadingID";

    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock_Light); //Used for theme switching in samples
        super.onCreate(savedInstanceState);
        setContentView(R.layout.empty);
        
        Intent intent = getIntent();
        ForumID = intent.getStringExtra(ListModuleItemActivity2.EXTRA_MESSAGE_ID);
        CourseCode = intent.getStringExtra(ListModuleItemActivity2.EXTRA_MESSAGE_COURSECODE);
        try{
        	isRefresh = savedInstanceState.getBoolean("isRefresh");
    	}catch(Exception ex){
	    }
        setActionBar();
    }
    
    @Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  savedInstanceState.putBoolean("isRefresh", isRefresh);
	}
    
    public void getForum(){
    	if(!isRefresh){
	        if(!IVLEToken.isOffline()){
		        if(IsNetworkAvailable.check(context)){
		            item.setActionView(R.layout.progressbarindeterminatesmall);
		        	getForumPostTask = new GetForumTask(this);
			        getForumPostTask.execute(ForumID);
		        }else{
		        	IVLEToken.setOffline(true);
		        	Toast.makeText(context, "Sorry, currently OFFLINE MODE dose NOT support Furoms." , Toast.LENGTH_LONG).show();
		        }
	        }else{
	        	Toast.makeText(context, "Sorry, currently OFFLINE MODE dose NOT support Furoms." , Toast.LENGTH_LONG).show();
	        }
    	}
    }
    
    @Override
    public void onDestroy(){
    	if(this.getForumPostTask!=null)
    		this.getForumPostTask.cancel(true);
    	super.onDestroy();
    }
    
	public void onAsyncTaskComplete(String result) {
		try {
			isEmpty = getForumPostTask.get();
		} catch (Exception e) {
		}
		list = ForumData.get(ForumID);
		if(list!=null)
        	setListView();
		if(item!=null)
			item.setActionView(null);
		isRefresh = true;
	}
    
    private void setListView(){
    	TextView tv = (TextView) findViewById(R.id.textView1);
    	if(!isEmpty){
    		tv.setVisibility(View.GONE);
	    	ForumSeparatedListAdapter adapter = new ForumSeparatedListAdapter(this, list);
	        setListAdapter(adapter);
	        
	        ListView lv = getListView();
	        lv.setTextFilterEnabled(true);
	
	        lv.setOnItemClickListener(new OnItemClickListener() {
	          public void onItemClick(AdapterView<?> parent, View view,
	              int position, long id) {
	        	  Intent intent = new Intent(ListForumPostActivity.this, ViewForumPostActivity.class);
		          intent.putExtra(MSG_PostID, list.get(position).get("ID"));
		          intent.putExtra(MSG_ForumID, ForumID);
		          if(list.get(position).containsKey("isNewPost")){
		        	  intent.putExtra("hasNewPost", true);
		        	  startActivityForResult(intent, 1);
		          }
		          else
		        	  startActivity(intent);
	          }
	        });
    	}
    	else{
    		tv.setVisibility(View.VISIBLE);
    	}
	}
    
    private void setActionBar(){
    	final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(false);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setSubtitle(CourseCode);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.layout.forum_menu, menu);
        item = menu.findItem(R.id.refresh);
        list = ForumData.get(ForumID);
        if(list!=null)
        	if(list.size()>0)
        		setListView();
        getForum();
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) 
    {
    	switch (item.getItemId()) {
	        case android.R.id.home:
	        	super.onBackPressed();
	        	break;
	        case R.id.refresh:
	        	this.item = item;
		        if(!IVLEToken.isOffline()){
			        if(IsNetworkAvailable.check(context)){
			            item.setActionView(R.layout.progressbarindeterminatesmall);
			        	getForumPostTask = new GetForumTask(this);
				        getForumPostTask.execute(ForumID);
			        }else{
			        	IVLEToken.setOffline(true);
			        	Toast.makeText(context, "Sorry, currently OFFLINE MODE dose NOT support Furoms." , Toast.LENGTH_LONG).show();
			        }
		        }else{
		        	Toast.makeText(context, "Sorry, currently OFFLINE MODE dose NOT support Furoms." , Toast.LENGTH_LONG).show();
		        }
	        	break;
	        case R.id.newPost:
	        	if (list!=null){
		        	ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
		        	for(Map<String, String> map:list){
		        		if(map.containsKey("Title"))
		        			adapter.add(map.get("Title"));
		        	}
	            	AlertDialog.Builder builder = new AlertDialog.Builder(context);
	            	builder.setTitle("Which Heading to post to:");
	            	builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
	            	    public void onClick(DialogInterface dialog, int item) {
	            	    	newPost(list.get(item).get("ID"));
	            	    	}
	            	    
	            	});
	            	AlertDialog alert = builder.create();
	            	alert.show();
		        	}
	        	break;
    	}
          return true;
    }
    
    public void newPost(String ID){
    	Intent intent = new Intent(context, PostForumActivity.class);
        intent.putExtra(MSG_HeadingID, ID);
        intent.putExtra("newPost", true);
        startActivityForResult(intent, 0);
    }
    
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) {     
    	super.onActivityResult(requestCode, resultCode, data); 
    	switch(requestCode) { 
	        case 0 :
	        	if (resultCode == Activity.RESULT_OK) { 
	        		boolean posted = data.getBooleanExtra(PostForumActivity.MSG_PSOTED, false);
	        		if(posted){
	        			isRefresh = false;
	        			getForum();
	        		}
	        	}
	        	break;
	        case 1 :
	        	getForum();
	        	break;
      	} 
    }
}
